package com.sky.task;

import com.github.pagehelper.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 老杨
 * @version 1.0
 *
 * 处理 订单的定时任务
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    OrderMapper orderMapper;


    /**
     * 每 15 分钟 执行一次
     * 检查 是否有超时未支付订单
     */
    @Scheduled(cron = "0 0/15 * * * ? ")
    public void unpaidOrder(){
        log.info("检查 是否有未支付订单中...{}",LocalDateTime.now());
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(Orders.PENDING_PAYMENT);
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
        List<Orders> result = page.getResult();
        if (result != null && result.size() > 0){
            //有未支付订单
            //检查是否超时
            for(Orders orders : result){
                LocalDateTime orderTime = orders.getOrderTime();
                Duration between = Duration.between(orderTime, LocalDateTime.now());
                if( between.toMinutes() > 15){
                    //超过15分钟未支付的，取消该订单
                    orders.setStatus(Orders.CANCELLED);
                    orders.setCancelReason("订单超时，自动取消");
                    orders.setCancelTime(LocalDateTime.now());
                    orderMapper.update(orders);
                }
            }
        }

        //没有未支付订单
    }


    /**
     * 每天凌晨1点 执行一次
     * 将 派送中 订单改为 已完成
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void finishOrder(){
        log.info("检查 还在派送中订单...{}",LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> result = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (result != null && result.size() > 0){
            //只要 有派送订单，且是上一天的订单，全部改为 已完成
            for(Orders orders:result){
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
